package algorithms.que14;

import algorithms.que13.Stack1;

import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;

/**
 * @功能
 * @创建时间 2020/9/13
 */
public class E1d4d32 <Item>  implements Iterable<Item>{
    Item[] items;
    int pushPopCount;
    int size;
    int max=10;
    int count; //对数组操作次数
    int m; //
    public E1d4d32(){
        items=(Item[]) new Object[max];
        size=0;
        count++;
        m++;
    }
    public void push(Item item){
        items[size++]=item;
        if(size>max/2){
        resize(2*max);
        }
        count++;
        pushPopCount++;
        m++;
    }

    public Item pop(){
        Item item=items[size-1];
        items[size--]=null;
        if(size<max/2&&size>5){
        resize(max/2);
        }
        count++;
        pushPopCount++;
        m++;
        return item;
    }
    public void resize(int max){
        this.max=max;
       Item[] newitems=(Item[]) new Object[max];
        for (int i = 0; i < size; i++) {
            newitems[i]=items[i];
        }
        items=newitems;
        count++;

    }
    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }



    private class ListIterator implements Iterator<Item>
    {   private int i=1;
        private Item[] current=items;
        private int originatedPushPopCount;
        public ListIterator()
        {
            originatedPushPopCount=pushPopCount;
        }
        public boolean hasNext(){return current!=null;}
        public void remove(){}
        public Item next()
        {
            if(originatedPushPopCount!=pushPopCount)
                throw new java.util.ConcurrentModificationException();
            Item item=current[size-i];
            i++;
            count++;
            return item;
        }//end next
    }//end class ListIterator
}
